<template>
  <div class="starrocks-generic-data-quality-form">
    <el-form label-width="140px" :model="localValue">
      <section class="form-section">
        <div class="section-title">
          <el-icon class="data-source-icon"><Histogram /></el-icon>
          <span>数据源与时间范围</span>
        </div>
        <el-form-item label="StarRocks 数据源" required>
          <DataSourceSelector
            v-model="sharedDataSourceId"
            service-type="starrocks"
            placeholder="选择 StarRocks 数据源（源表和目标表共用）"
            @change="handleDataSourceChange"
          />
        </el-form-item>
        <ReportTimeRangePicker
          v-model="localValue.time_range"
          @change="handleTimeRangeChange"
        />
      </section>

      <section class="form-section">
        <div class="section-title">
          <el-icon class="source-table-icon"><Collection /></el-icon>
          <span>源表配置</span>
        </div>
        <SourceTableConfig
          :model-value="localValue.source_tables"
          :data-source-product_id="sharedDataSourceId"
          :global-time-range="localValue.time_range"
          @update:model-value="handleSourceTablesChange"
        />
      </section>

      <section class="form-section">
        <div class="section-title">
          <el-icon class="target-table-icon"><List /></el-icon>
          <span>目标表配置</span>
        </div>
        <el-row :gutter="16" class="target-filter-toggle-row">
          <el-col :span="12">
            <el-form-item label="启用字段过滤">
              <el-switch v-model="targetFilterEnabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用统计字段">
              <el-switch v-model="targetStatEnabled" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="数据库" required>
              <el-select
                v-model="localValue.target_table_config.database_name"
                placeholder="请选择数据库"
                :loading="targetDatabasesLoading"
                filterable
                style="width: 100%"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
                @change="handleTargetDatabaseChange"
              >
                <el-option
                  v-for="db in targetDatabases"
                  :key="db"
                  :label="db"
                  :value="db"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表名" required>
              <el-select
                v-model="localValue.target_table_config.table_name"
                placeholder="请选择表"
                :loading="targetTablesLoading"
                filterable
                style="width: 100%"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
                @change="handleTargetTableChange"
              >
                <el-option
                  v-for="table in targetTables"
                  :key="table.table_name"
                  :label="table.table_name"
                  :value="table.table_name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="关联字段" required>
              <el-select
                v-model="localValue.target_table_config.join_field"
                placeholder="请选择关联字段"
                :loading="targetFieldsLoading"
                filterable
                style="width: 100%"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
                @change="emitParams"
              >
                <el-option
                  v-for="field in targetFields"
                  :key="field.field_name"
                  :label="field.field_name"
                  :value="field.field_name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="localValue.time_range?.time_range_type !== 'all'" :span="12">
            <el-form-item label="时间字段">
              <el-select
                v-model="localValue.target_table_config.time_field"
                placeholder="选择时间字段，如 etl_date"
                :loading="targetFieldsLoading"
                filterable
                style="width: 100%"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
                @change="emitParams"
              >
                <el-option
                  v-for="field in targetFields"
                  :key="field.field_name"
                  :label="field.field_name"
                  :value="field.field_name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 筛选条件配置 -->
        <template v-if="targetFilterEnabled">
          <el-divider />
          <div class="section-subtitle">
            <el-icon><Filter /></el-icon>
            <span>筛选条件（可选）</span>
          </div>
          <div v-for="(condition, index) in (localValue.target_table_config.filter_conditions || [])" :key="index" class="filter-condition-row">
          <el-row :gutter="16">
            <el-col :span="6">
              <el-form-item :label="index === 0 ? '字段' : ''" label-width="60px">
                <el-select
                  v-model="condition.field"
                  placeholder="选择字段"
                  :loading="targetFieldsLoading"
                  filterable
                  style="width: 100%"
                  popper-class="batch-dialog-select-popper"
                  popper-append-to-body
                  @change="emitParams"
                >
                  <el-option
                    v-for="field in targetFields"
                    :key="field.field_name"
                    :label="field.field_name"
                    :value="field.field_name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :label="index === 0 ? '操作符' : ''" label-width="60px">
                <el-select
                  v-model="condition.operator"
                  placeholder="操作符"
                  style="width: 100%"
                  popper-class="batch-dialog-select-popper"
                  popper-append-to-body
                  @change="emitParams"
                >
                  <el-option label="=" value="=" />
                  <el-option label="!=" value="!=" />
                  <el-option label=">" value=">" />
                  <el-option label="<" value="<" />
                  <el-option label=">=" value=">=" />
                  <el-option label="<=" value="<=" />
                  <el-option label="IN" value="IN" />
                  <el-option label="LIKE" value="LIKE" />
                  <el-option label="NOT LIKE" value="NOT LIKE" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item :label="index === 0 ? '值' : ''" label-width="60px">
                <el-input
                  v-model="condition.value"
                  placeholder="输入值"
                  @change="emitParams"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label-width="0">
                <el-button
                  type="danger"
                  size="small"
                  @click="removeFilterCondition(index)"
                >
                  删除
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
          <el-button
            type="primary"
            size="small"
            :icon="Plus"
            @click="addFilterCondition"
          >
            添加筛选条件
          </el-button>
        </template>

        <!-- 统计字段配置 -->
        <template v-if="targetStatEnabled">
          <el-divider />
          <div class="section-subtitle">
            <el-icon><DataAnalysis /></el-icon>
            <span>统计字段（可选）</span>
          </div>
          <el-form-item>
            <StatFieldsConfig
              v-model="localValue.target_table_config.stat_fields"
              :available-fields="targetFields.map((f) => f.field_name)"
              @change="handleStatFieldsChange"
            />
          </el-form-item>
        </template>
      </section>

      <section class="form-section">
        <div class="section-title">
          <el-icon class="threshold-icon"><Tickets /></el-icon>
          <span>阈值配置</span>
        </div>
        
        <div class="threshold-container">
          <!-- 同步率阈值设置 -->
          <div class="threshold-item">
            <div class="item-header">
              <el-icon><Histogram /></el-icon>
              <span>同步率阈值 (%)</span>
              <el-tooltip content="当同步率低于此阈值时，数据状态将显示为'同步率过低'" placement="top">
                <el-icon class="help-icon"><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
            
            <div class="threshold-control">
              <el-slider
                v-model="localValue.filter_rules.sync_rate_threshold"
                :min="0"
                :max="100"
                :step="1"
                :marks="thresholdMarks"
                :format-tooltip="formatTooltip"
                @change="emitParams"
                class="threshold-slider"
              />
              
              <div class="threshold-input-group">
                <el-input-number
                  v-model="localValue.filter_rules.sync_rate_threshold"
                  :min="0"
                  :max="100"
                  :step="1"
                  controls-position="right"
                  @change="emitParams"
                  class="threshold-input"
                />
                <span class="unit">%</span>
              </div>
            </div>
          </div>
          
          <!-- 快捷阈值设置 -->
          <div class="quick-thresholds">
            <div class="quick-header">
              <el-icon><Star /></el-icon>
              <span>快捷设置</span>
            </div>
            <div class="quick-buttons">
              <el-button 
                v-for="preset in thresholdPresets" 
                :key="preset.label"
                size="small"
                :type="preset.value === localValue.filter_rules.sync_rate_threshold ? 'primary' : 'default'"
                @click="setThreshold(preset.value)"
              >
                {{ preset.label }}
              </el-button>
            </div>
          </div>
          
          <!-- 阈值预览 -->
          <div class="threshold-preview">
            <div class="preview-header">
              <el-icon><View /></el-icon>
              <span>阈值效果预览</span>
            </div>
            <div class="preview-content">
              <div class="preview-item">
                <span class="label">当前阈值:</span>
                <el-tag type="primary" size="small">{{ localValue.filter_rules.sync_rate_threshold }}%</el-tag>
              </div>
              <div class="status-examples">
                <div class="status-item normal">
                  <el-icon color="#67c23a"><CircleCheck /></el-icon>
                  <span>正常: ≥ {{ localValue.filter_rules.sync_rate_threshold }}%</span>
                </div>
                <div class="status-item warning">
                  <el-icon color="#e6a23c"><Warning /></el-icon>
                  <span>同步率过低: 0% ~ {{ localValue.filter_rules.sync_rate_threshold - 1 }}%</span>
                </div>
                <div class="status-item error">
                  <el-icon color="#f56c6c"><CircleClose /></el-icon>
                  <span>未同步: 0%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section class="form-section">
        <div class="section-title">
          <el-icon><Tickets /></el-icon>
          <span>显示字段</span>
        </div>
        <el-checkbox-group
          v-model="localValue.display_fields"
          class="display-fields"
          @change="emitParams"
        >
          <el-checkbox
            v-for="field in displayFieldOptions"
            :key="field.value"
            :label="field.value"
          >
            {{ field.label }}
          </el-checkbox>
        </el-checkbox-group>

        <el-divider />

        <el-row :gutter="16" class="field-label-toggle-row">
          <el-col :span="12">
            <div class="field-label-toggle-title">
              <el-icon><Tickets /></el-icon>
              <span>启用字段标签设置</span>
            </div>
          </el-col>
          <el-col :span="12" class="field-label-toggle-switch">
            <el-switch v-model="fieldLabelsEnabled" />
          </el-col>
        </el-row>

        <template v-if="fieldLabelsEnabled">
          <el-card shadow="never" class="field-label-card">
            <div class="field-label-help">
              自定义字段的中文显示名称，用于报表输出。留空则使用默认名称。
            </div>
            <el-table :data="fieldLabelsTable" border size="small" style="width: 100%" class="field-label-table">
              <el-table-column prop="fieldName" label="英文字段名" width="200">
                <template #default="{ row }">
                  <code class="field-code">{{ row.fieldName }}</code>
                </template>
              </el-table-column>
              <el-table-column prop="defaultLabel" label="默认中文名" width="200">
                <template #default="{ row }">
                  <span class="default-label">{{ row.defaultLabel }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="customLabel" label="自定义中文名">
                <template #default="{ row }">
                  <el-input
                    :model-value="row.customLabel"
                    @update:model-value="(val) => handleFieldLabelChange(row.fieldName, val)"
                    :placeholder="`留空使用默认名称：${row.defaultLabel}`"
                    size="small"
                    class="custom-input"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </template>
      </section>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, defineExpose, computed } from 'vue'
// @ts-ignore
import api from '@/utils/api.js'
// @ts-ignore
import { createLogger } from '@/utils/logger.js'
import { 
  Collection, Filter, Histogram, List, Tickets, DataAnalysis, Plus, 
  QuestionFilled, View, Star, CircleCheck, CircleClose, Warning 
} from '@element-plus/icons-vue'
import DataSourceSelector from '../../shared/DataSourceSelector.vue'
import SourceTableConfig from '../../shared/SourceTableConfig.vue'
import ReportTimeRangePicker from '../../shared/ReportTimeRangePicker.vue'
import StatFieldsConfig from '../../shared/StatFieldsConfig.vue'
import type { TemplateMeta } from '../registry'

interface GenericDataQualityParams {
  source_tables: {
    data_source_id: number | null
    databases: Array<{
      database_name: string
      table_names: string[]
      tables: Array<{
        table_name: string
        distinct_field: string
        time_field: string
        use_distinct: boolean
      }>
      filter_conditions?: Array<{
        field: string
        operator: string
        value: string
      }>
      stat_fields?: Record<string, any>
    }>
    time_range_type: string
    time_start: string | null
    time_end: string | null
  }
  target_table_config: {
    data_source_id: number | null
    database_name: string
    table_name: string
    join_field: string
    time_field: string
    filter_conditions: Array<{
      field: string
      operator: string
      value: string
    }>
    stat_fields: Record<string, any>
    time_range_type?: string
    time_start?: string | null
    time_end?: string | null
  }
  filter_rules: {
    sync_rate_threshold: number
  }
  display_fields: string[]
  field_labels?: Record<string, string>
  time_range?: {
    time_range_type: string
    time_start: string | null
    time_end: string | null
  }
}

const props = defineProps<{
  modelValue: GenericDataQualityParams | null
  templateMeta?: TemplateMeta | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: GenericDataQualityParams): void
  (e: 'validate', payload: { valid: boolean; errors: string[] }): void
}>()

const componentLogger = createLogger('StarrocksGenericDataQualityForm')

const requiredDisplayFields = ['source_table', 'target_table']

const defaultValue = (): GenericDataQualityParams => ({
  source_tables: {
    data_source_id: null,
    databases: [
      {
        database_name: '',
        table_names: [],
        tables: [
          {
            table_name: '',
            distinct_field: 'product_id',
            time_field: 'etl_date',
            use_distinct: true
          }
        ],
        filter_conditions: [],
        stat_fields: {}
      }
    ],
    time_range_type: 'all',
    time_start: null,
    time_end: null
  },
  target_table_config: {
    data_source_id: null,
    database_name: '',
    table_name: '',
    join_field: 'product_id',
    time_field: 'etl_date',
    filter_conditions: [],
    stat_fields: {}
  },
  filter_rules: {
    sync_rate_threshold: 80
  },
  display_fields: [
    'source_table',
    'target_table',
    'source_total_count',
    'target_total_count',
    'sync_rate',
    'data_status'
  ],
  field_labels: {
    source_table: '源表',
    target_table: '目标表',
    source_total_count: '源表总数',
    target_total_count: '目标表总数',
    sync_rate: '同步率',
    data_status: '数据状态'
  },
  time_range: {
    time_range_type: 'all',
    time_start: null,
    time_end: null
  }
})

const localValue = reactive<GenericDataQualityParams>({
  ...defaultValue(),
  ...(props.modelValue || {})
})

const ensureRequiredDisplayFields = () => {
  if (!Array.isArray(localValue.display_fields)) {
    localValue.display_fields = []
  }
  let changed = false
  requiredDisplayFields
    .slice()
    .reverse()
    .forEach((field) => {
      if (!localValue.display_fields.includes(field)) {
        localValue.display_fields.unshift(field)
        changed = true
      }
    })
  return changed
}

const sharedDataSourceId = ref<number | null>(localValue.source_tables.data_source_id ?? null)

const targetDatabases = ref<string[]>([])
const targetDatabasesLoading = ref(false)
const targetTables = ref<any[]>([])
const targetTablesLoading = ref(false)
const targetFields = ref<any[]>([])
const targetFieldsLoading = ref(false)

// 开关控制
const targetFilterEnabled = ref(
  !!(localValue.target_table_config.filter_conditions && localValue.target_table_config.filter_conditions.length > 0)
)

const targetStatEnabled = ref(
  !!(localValue.target_table_config.stat_fields && Object.keys(localValue.target_table_config.stat_fields).length > 0)
)

// 基础字段选项（始终显示）
const baseDisplayFieldOptions = [
  { value: 'source_table', label: '源表' },
  { value: 'target_table', label: '目标表' },
  { value: 'source_total_count', label: '源表总数' },
  { value: 'target_total_count', label: '目标表总数' },
  { value: 'sync_rate', label: '同步率' },
  { value: 'data_status', label: '数据状态' }
]

// 动态字段选项（从统计字段配置中提取）
const dynamicDisplayFieldOptions = computed(() => {
  const options: Array<{ value: string; label: string }> = []
  
  // 目标表统计字段
  const targetStatFields = localValue.target_table_config.stat_fields || {}
  for (const [fieldName, fieldConfig] of Object.entries(targetStatFields)) {
    if (!fieldConfig || typeof fieldConfig !== 'object') continue
    
    const outputFields = fieldConfig.output_fields || []
    outputFields.forEach((outputField: string) => {
      if (outputField && !options.find(opt => opt.value === outputField)) {
        const label = localValue.field_labels?.[outputField] || outputField
        options.push({ value: outputField, label })
      }
    })
  }
  
  // 源表统计字段（从所有数据库配置中收集）
  const sourceDatabases = localValue.source_tables.databases || []
  for (const dbConfig of sourceDatabases) {
    const sourceStatFields = dbConfig.stat_fields || {}
    for (const [fieldName, fieldConfig] of Object.entries(sourceStatFields)) {
      if (!fieldConfig || typeof fieldConfig !== 'object') continue
      
      const outputFields = fieldConfig.output_fields || []
      outputFields.forEach((outputField: string) => {
        if (outputField && !options.find(opt => opt.value === outputField)) {
          const label = localValue.field_labels?.[outputField] || outputField
          options.push({ value: outputField, label })
        }
      })
    }
  }
  
  return options
})

// 合并的字段选项
const displayFieldOptions = computed(() => {
  return [...baseDisplayFieldOptions, ...dynamicDisplayFieldOptions.value]
})

const getDisplayFieldOrder = () => [
  ...baseDisplayFieldOptions.map((opt) => opt.value),
  ...dynamicDisplayFieldOptions.value.map((opt) => opt.value)
]

const sortDisplayFields = () => {
  if (!Array.isArray(localValue.display_fields)) {
    localValue.display_fields = []
  }
  const uniqueSelected = Array.from(new Set(localValue.display_fields))
  const sorted: string[] = []

  getDisplayFieldOrder().forEach((field) => {
    if (uniqueSelected.includes(field)) {
      sorted.push(field)
    }
  })

  uniqueSelected.forEach((field) => {
    if (!sorted.includes(field)) {
      sorted.push(field)
    }
  })

  const changed =
    sorted.length !== localValue.display_fields.length ||
    sorted.some((field, idx) => field !== localValue.display_fields[idx])

  if (changed) {
    localValue.display_fields = sorted
  }
}

ensureRequiredDisplayFields()
sortDisplayFields()

const fieldLabelsTable = computed(() =>
  displayFieldOptions.value.map((opt) => ({
    fieldName: opt.value,
    defaultLabel: opt.label,
    customLabel: localValue.field_labels?.[opt.value] || ''
  }))
)

const fieldLabelsEnabled = ref(
  (() => {
    if (!localValue.field_labels || Object.keys(localValue.field_labels).length === 0) {
      return false
    }
    for (const field of localValue.display_fields) {
      const option = displayFieldOptions.value.find((opt) => opt.value === field)
      if (option) {
        const currentLabel = localValue.field_labels[field]
        const defaultLabel = option.label
        if (currentLabel !== defaultLabel) {
          return true
        }
      }
    }
    return false
  })()
)

const handleFieldLabelChange = (fieldName: string, value: string) => {
  if (!localValue.field_labels) {
    ;(localValue as any).field_labels = {}
  }
  if (value && value.trim()) {
    (localValue.field_labels as Record<string, string>)[fieldName] = value.trim()
  } else if (localValue.field_labels) {
    delete (localValue.field_labels as Record<string, string>)[fieldName]
  }
  emitParams()
}

// 阈值相关数据和方法
const thresholdMarks = {
  50: '50%',
  70: '70%',
  80: '80%',
  90: '90%',
  95: '95%'
}

// 预设阈值选项
const thresholdPresets = [
  { label: '严格 (90%)', value: 90 },
  { label: '标准 (80%)', value: 80 },
  { label: '宽松 (70%)', value: 70 },
  { label: '极宽松 (50%)', value: 50 }
]

const formatTooltip = (value: number) => {
  return `${value}%`
}

const setThreshold = (value: number) => {
  localValue.filter_rules.sync_rate_threshold = value
  emitParams()
}

const addFilterCondition = () => {
  if (!localValue.target_table_config.filter_conditions) {
    localValue.target_table_config.filter_conditions = []
  }
  localValue.target_table_config.filter_conditions.push({
    field: '',
    operator: '=',
    value: ''
  })
  targetFilterEnabled.value = true
  emitParams()
}

const removeFilterCondition = (index: number) => {
  if (localValue.target_table_config.filter_conditions) {
    localValue.target_table_config.filter_conditions.splice(index, 1)
    // 如果删除后没有筛选条件了，更新开关状态
    if (localValue.target_table_config.filter_conditions.length === 0) {
      targetFilterEnabled.value = false
    }
    emitParams()
  }
}


const writeRootTimeRange = () => {
  if (!localValue.time_range) {
    localValue.time_range = {
      time_range_type: 'all',
      time_start: null,
      time_end: null
    }
  }
  ;(localValue as any).time_range_type = localValue.time_range.time_range_type
  ;(localValue as any).time_start = localValue.time_range.time_start
  ;(localValue as any).time_end = localValue.time_range.time_end
}

const emitParams = () => {
  ensureRequiredDisplayFields()
  sortDisplayFields()
  writeRootTimeRange()
  if (fieldLabelsEnabled.value) {
    if (!localValue.field_labels) {
      localValue.field_labels = {}
    }
    localValue.display_fields.forEach((field) => {
      if (!localValue.field_labels![field]) {
        const option = displayFieldOptions.value.find((opt) => opt.value === field)
        if (option) {
          localValue.field_labels![field] = option.label
        }
      }
    })
  } else {
    localValue.field_labels = {}
  }
  emit('update:modelValue', JSON.parse(JSON.stringify(localValue)))
}

const handleSourceTablesChange = (value: GenericDataQualityParams['source_tables']) => {
  const current = localValue.source_tables || defaultValue().source_tables
  if (value) {
    localValue.source_tables = {
      data_source_id: value.data_source_id ?? current.data_source_id ?? null,
      databases: value.databases ?? current.databases ?? [],
      time_range_type: value.time_range_type ?? current.time_range_type,
      time_start: value.time_start ?? current.time_start,
      time_end: value.time_end ?? current.time_end
    }
  }
  emitParams()
}

const handleDataSourceChange = (value: number | null) => {
  sharedDataSourceId.value = value
  localValue.source_tables.data_source_id = value
  localValue.target_table_config.data_source_id = value
  localValue.target_table_config.database_name = ''
  localValue.target_table_config.table_name = ''
  targetDatabases.value = []
  targetTables.value = []
  targetFields.value = []
  emitParams()
}

const fetchTargetDatabases = async () => {
  if (!sharedDataSourceId.value) {
    targetDatabases.value = []
    return
  }
  try {
    targetDatabasesLoading.value = true
    const response = await api.get('/reports/starrocks-databases', {
      params: { config_id: sharedDataSourceId.value }
    })
    if (response.data.success) {
      targetDatabases.value = response.data.data || []
    }
  } catch (error) {
    componentLogger.error('获取目标库列表失败', error)
  } finally {
    targetDatabasesLoading.value = false
  }
}

const fetchTargetTables = async () => {
  if (!sharedDataSourceId.value || !localValue.target_table_config.database_name) {
    targetTables.value = []
    return
  }
  try {
    targetTablesLoading.value = true
    const response = await api.get('/reports/starrocks-tables', {
      params: {
        config_id: sharedDataSourceId.value,
        database: localValue.target_table_config.database_name
      }
    })
    if (response.data.success) {
      targetTables.value = response.data.data || []
    }
  } catch (error) {
    componentLogger.error('获取目标表列表失败', error)
  } finally {
    targetTablesLoading.value = false
  }
}

const fetchTargetFields = async () => {
  if (
    !sharedDataSourceId.value ||
    !localValue.target_table_config.database_name ||
    !localValue.target_table_config.table_name
  ) {
    targetFields.value = []
    return
  }
  try {
    targetFieldsLoading.value = true
    const response = await api.get('/reports/starrocks-table-fields', {
      params: {
        config_id: sharedDataSourceId.value,
        database: localValue.target_table_config.database_name,
        table_name: localValue.target_table_config.table_name
      }
    })
    if (response.data.success) {
      targetFields.value = response.data.data || []
    }
  } catch (error) {
    componentLogger.error('获取目标表字段列表失败', error)
  } finally {
    targetFieldsLoading.value = false
  }
}


const handleTargetDatabaseChange = () => {
  localValue.target_table_config.table_name = ''
  localValue.target_table_config.join_field = 'product_id'
  localValue.target_table_config.time_field = 'etl_date'
  targetTables.value = []
  targetFields.value = []
  emitParams()
}

const handleTargetTableChange = () => {
  emitParams()
}

// 处理统计字段变化，自动添加输出字段到显示字段
const handleStatFieldsChange = (statFields: Record<string, any>) => {
  // 先获取当前所有统计字段的输出字段名（用于清理）
  const previousOutputFields = new Set<string>()
  const currentStatFields = localValue.target_table_config.stat_fields || {}
  for (const [fieldName, fieldConfig] of Object.entries(currentStatFields)) {
    if (!fieldConfig || typeof fieldConfig !== 'object') continue
    // 输出字段名现在是必填的，直接使用配置的输出字段名
    const configOutputFields = fieldConfig.output_fields || []
    configOutputFields.forEach((f: string) => previousOutputFields.add(f))
  }
  
  if (!statFields || Object.keys(statFields).length === 0) {
    // 如果清空了统计字段，移除相关的显示字段（保留基础字段）
    const baseFields = baseDisplayFieldOptions.map(opt => opt.value)
    localValue.display_fields = localValue.display_fields.filter(
      field => baseFields.includes(field) || !previousOutputFields.has(field)
    )
    sortDisplayFields()
    emitParams()
    return
  }
  
  // 收集所有统计字段的输出字段名（输出字段名现在是必填的）
  const outputFields: string[] = []
  for (const [fieldName, fieldConfig] of Object.entries(statFields)) {
    if (!fieldConfig || typeof fieldConfig !== 'object') continue
    
    const configOutputFields = fieldConfig.output_fields || []
    outputFields.push(...configOutputFields)
  }
  
  // 自动添加输出字段到显示字段（如果还没有）
  const currentFields = new Set(localValue.display_fields)
  let updated = false
  outputFields.forEach(outputField => {
    if (outputField && !currentFields.has(outputField)) {
      localValue.display_fields.push(outputField)
      updated = true
    }
  })
  
  if (updated) {
    sortDisplayFields()
    emitParams()
  }
}

const handleTimeRangeChange = (value: GenericDataQualityParams['time_range']) => {
  localValue.time_range = value || {
    time_range_type: 'all',
    time_start: null,
    time_end: null
  }
  localValue.source_tables.time_range_type = localValue.time_range.time_range_type
  localValue.source_tables.time_start = localValue.time_range.time_start
  localValue.source_tables.time_end = localValue.time_range.time_end
  localValue.target_table_config.time_range_type = localValue.time_range.time_range_type
  localValue.target_table_config.time_start = localValue.time_range.time_start
  localValue.target_table_config.time_end = localValue.time_range.time_end
  writeRootTimeRange()
  emitParams()
}

watch(
  () => props.modelValue,
  (val) => {
    if (!val) return
    const newValue = JSON.parse(JSON.stringify(val))
    const currentValueStr = JSON.stringify(localValue)
    const newValueStr = JSON.stringify(newValue)
    
    if (currentValueStr === newValueStr) return
    
    const merged = { ...defaultValue(), ...newValue }
    for (const key in merged) {
      if (merged.hasOwnProperty(key)) {
        const mergedValue = merged[key]
        const defaultValueObj = defaultValue()[key]
        if (
          mergedValue &&
          typeof mergedValue === 'object' &&
          !Array.isArray(mergedValue) &&
          defaultValueObj &&
          typeof defaultValueObj === 'object' &&
          !Array.isArray(defaultValueObj)
        ) {
          merged[key] = { ...defaultValueObj, ...mergedValue }
        }
      }
    }
    Object.assign(localValue, merged)
    ensureRequiredDisplayFields()
    sortDisplayFields()
    writeRootTimeRange()
    
    if (localValue.time_range) {
      localValue.source_tables.time_range_type = localValue.time_range.time_range_type
      localValue.source_tables.time_start = localValue.time_range.time_start
      localValue.source_tables.time_end = localValue.time_range.time_end
      localValue.target_table_config.time_range_type = localValue.time_range.time_range_type
      localValue.target_table_config.time_start = localValue.time_range.time_start
      localValue.target_table_config.time_end = localValue.time_range.time_end
    }
    
    if (localValue.source_tables?.data_source_id !== undefined) {
      sharedDataSourceId.value = localValue.source_tables.data_source_id
    }
    
    // 更新开关状态
    targetFilterEnabled.value = !!(
      localValue.target_table_config.filter_conditions && 
      localValue.target_table_config.filter_conditions.length > 0
    )
    targetStatEnabled.value = !!(
      localValue.target_table_config.stat_fields && 
      Object.keys(localValue.target_table_config.stat_fields).length > 0
    )
    
    if (!localValue.field_labels || Object.keys(localValue.field_labels).length === 0) {
      fieldLabelsEnabled.value = false
    } else {
      let hasCustomLabels = false
      for (const field of localValue.display_fields) {
        const option = displayFieldOptions.value.find((opt) => opt.value === field)
        if (option) {
          const currentLabel = localValue.field_labels[field]
          const defaultLabel = option.label
          if (currentLabel !== defaultLabel) {
            hasCustomLabels = true
            break
          }
        }
      }
      fieldLabelsEnabled.value = hasCustomLabels
    }
  },
  { deep: true }
)

watch(
  sharedDataSourceId,
  (newId) => {
    localValue.source_tables.data_source_id = newId
    localValue.target_table_config.data_source_id = newId
    if (!newId) {
      targetDatabases.value = []
      targetTables.value = []
      targetFields.value = []
      return
    }
    fetchTargetDatabases()
  },
  { immediate: true }
)

watch(
  () => localValue.target_table_config.database_name,
  (databaseName) => {
    if (!sharedDataSourceId.value || !databaseName) {
      targetTables.value = []
      targetFields.value = []
      return
    }
    fetchTargetTables()
  },
  { immediate: true }
)

watch(
  () => localValue.target_table_config.table_name,
  (tableName) => {
    if (
      !sharedDataSourceId.value ||
      !localValue.target_table_config.database_name ||
      !tableName
    ) {
      targetFields.value = []
      return
    }
    fetchTargetFields()
  },
  { immediate: true }
)

watch(
  () => props.templateMeta,
  (meta) => {
    if (meta?.defaultParams) {
      Object.assign(localValue, defaultValue(), JSON.parse(JSON.stringify(meta.defaultParams)))
      ensureRequiredDisplayFields()
      sortDisplayFields()
      emitParams()
    }
  },
  { immediate: false }
)

watch(fieldLabelsEnabled, (enabled) => {
  if (!enabled) {
    localValue.field_labels = {}
    emitParams()
  }
})

// 监听开关状态变化
watch(targetFilterEnabled, (enabled) => {
  if (enabled) {
    // 打开过滤时，如果没有筛选条件，添加一个空的
    if (!localValue.target_table_config.filter_conditions || localValue.target_table_config.filter_conditions.length === 0) {
      localValue.target_table_config.filter_conditions = [{
        field: '',
        operator: '=',
        value: ''
      }]
    }
    emitParams()
  } else {
    // 关闭过滤时清空筛选条件
    localValue.target_table_config.filter_conditions = []
    emitParams()
  }
})

watch(targetStatEnabled, (enabled) => {
  if (!enabled) {
    // 关闭统计字段时清空配置
    localValue.target_table_config.stat_fields = {}
    // 移除统计字段相关的显示字段
    const statOutputFields = new Set<string>()
    const currentStatFields = localValue.target_table_config.stat_fields || {}
    for (const [fieldName, fieldConfig] of Object.entries(currentStatFields)) {
      if (!fieldConfig || typeof fieldConfig !== 'object') continue
      const configOutputFields = fieldConfig.output_fields || []
      configOutputFields.forEach((f: string) => statOutputFields.add(f))
    }
    const baseFields = baseDisplayFieldOptions.map(opt => opt.value)
    localValue.display_fields = localValue.display_fields.filter(
      field => baseFields.includes(field) || !statOutputFields.has(field)
    )
    sortDisplayFields()
    emitParams()
  }
})


// 监听统计字段变化，自动添加输出字段到显示字段
watch(
  () => localValue.target_table_config.stat_fields,
  (statFields) => {
    handleStatFieldsChange(statFields || {})
  },
  { deep: true }
)

watch(dynamicDisplayFieldOptions, () => {
  sortDisplayFields()
})

const validate = () => {
  const errors: string[] = []
  
  if (!sharedDataSourceId.value) {
    errors.push('请选择 StarRocks 数据源')
  }
  if (!localValue.target_table_config.database_name) {
    errors.push('请填写目标库名')
  }
  if (!localValue.target_table_config.table_name) {
    errors.push('请填写目标表名')
  }
  if (!localValue.target_table_config.join_field) {
    errors.push('请选择关联字段')
  }
  
  // 验证筛选条件
  if (localValue.target_table_config.filter_conditions) {
    for (let i = 0; i < localValue.target_table_config.filter_conditions.length; i++) {
      const condition = localValue.target_table_config.filter_conditions[i]
      if (condition.field && !condition.value) {
        errors.push(`筛选条件 ${i + 1}：请填写值`)
      }
      if (condition.value && !condition.field) {
        errors.push(`筛选条件 ${i + 1}：请选择字段`)
      }
    }
  }
  
  emit('validate', { valid: errors.length === 0, errors })
  return errors.length === 0
}

defineExpose({ validate })
</script>

<style scoped>
.form-section {
  margin-bottom: 24px;
  padding: 24px;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #1f2937;
  font-size: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f0f0;
}

.section-subtitle {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #606266;
  font-size: 14px;
}

.filter-condition-row {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.display-fields {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.field-label-toggle-row {
  margin: 20px 0 16px 0;
}

.field-label-toggle-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #606266;
}

.field-label-toggle-switch {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.field-label-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fafafa;
}

.field-label-help {
  margin-bottom: 16px;
  padding: 12px 16px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 6px;
  font-size: 14px;
  color: #1e40af;
  line-height: 1.5;
}

.default-label {
  color: #909399;
  font-size: 14px;
  font-weight: 500;
}

.field-code {
  background-color: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  color: #e74c3c;
  font-weight: 600;
  border: 1px solid #e4e7ed;
}

.target-filter-toggle-row {
  margin-bottom: 16px;
}

.threshold-icon {
  color: #e6a23c;
}

/* 阈值配置样式 */
.threshold-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background-color: #fafafa;
}

.threshold-item {
  margin-bottom: 20px;
}

.item-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 500;
  color: #303133;
}

.help-icon {
  color: #909399;
  font-size: 14px;
  cursor: help;
}

.threshold-control {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.threshold-slider {
  flex: 1;
  min-width: 200px;
  margin: 0;
}

.threshold-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.threshold-input {
  width: 100px;
}

.unit {
  color: #909399;
  font-size: 14px;
}

.quick-thresholds {
  margin-bottom: 20px;
}

.quick-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 500;
  color: #606266;
}

.quick-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.threshold-preview {
  margin-bottom: 0;
  padding: 12px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 8px;
}

.threshold-preview .preview-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-weight: 500;
  color: #1e40af;
}

.threshold-preview .preview-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.threshold-preview .preview-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.threshold-preview .label {
  color: #606266;
  font-weight: 500;
}

.status-examples {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

/* 滑块样式优化 */
.threshold-slider :deep(.el-slider__runway) {
  background-color: #e4e7ed;
}

.threshold-slider :deep(.el-slider__bar) {
  background: linear-gradient(90deg, #f56c6c 0%, #e6a23c 50%, #67c23a 100%);
}

.threshold-slider :deep(.el-slider__button) {
  border-color: #409eff;
}

.threshold-slider :deep(.el-slider__stop) {
  background-color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .threshold-control {
    flex-direction: column;
    gap: 12px;
  }
  
  .threshold-input-group {
    justify-content: center;
  }
  
  .status-examples {
    flex-direction: column;
    gap: 8px;
  }
  
  .quick-buttons {
    gap: 6px;
  }
}
</style>

